﻿using EYangFrame.DataAccess.Global;
using EYangFramewirk.Business.MessageSystem.Interfaces;
using EYangFramework.Common.Ninject;
using EYangFramework.Domain.Entitys.Entrys;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Message = EYangFramework.Domain.Entitys.Entrys.Message;

namespace EYangFramework.MessageSystem
{
    public partial class frm_MessageMain : EYangFramework.CommonForm.frm_BasicForm
    {
        Dictionary<Guid, string> allUsers = new Dictionary<Guid, string>();
        public frm_MessageMain()
        {
            InitializeComponent();
        }

        private void frmMessageMain_Load(object sender, EventArgs e)
        {
            SetTabVisible(tp_Detail, false);
            tv_List.Nodes.Clear();
            using (IBLLMessageMain bLLMessageMain = NinjectProvider.NinjectCore.GetService<IBLLMessageMain>())
            {
                List<Role> roles = bLLMessageMain.GetAllRoles().OrderBy(t=>t.ROLENAME).ToList();
                TreeNode root = new TreeNode();
                root.Tag = null;
                root.Text = "用户列表";
                BindTree(roles.Where(t => t.PARENT == null).ToList(), root);
                tv_List.Nodes.Add(root);
            }
            tv_List.ExpandAll();
        }
        private void BindTree(List<Role> roles,TreeNode node)
        {
            foreach (Role role in roles)
            {
                TreeNode currentNode = new TreeNode();
                currentNode.Text = role.ROLENAME;
                currentNode.Tag = null;
                node.Nodes.Add(currentNode);
                List<Role> childRoles = roles.Where(t => t.PARENT?.ID == role.ID).ToList();
                foreach (var user in role.USERS.Where(t => !t.ISDELETE).OrderBy(t => t.USERNAME))
                {
                    allUsers.Add(user.ID, user.USERNAME);
                    TreeNode userNode = new TreeNode();
                    userNode.Tag = user.ID;
                    userNode.Text = user.USERNAME;
                    currentNode.Nodes.Add(userNode);
                }
                if (childRoles.Count > 0)
                {
                    BindTree(childRoles, currentNode);
                }
            }
        }
        public override void ExecuteSingtonTimer(object sender, EventArgs args)
        {
            //base.ExecuteSingtonTimer(sender, args);
            BindMessage();
        }

        private void BindMessage()
        {
            Guid currentUserID = GlobalInfo.CurrentUser.ID;
            using (IBLLMessageMain bLLMessageMain = NinjectProvider.NinjectCore.GetService<IBLLMessageMain>())
            {
                List<Message> messages = bLLMessageMain.GetAllMessages(currentUserID);
                List<Message> noReadMessages = messages.Where(t => !t.ReadUser.Contains(currentUserID.ToString())).ToList();//获取到所有未读的消息
                if (radRead.Checked)//如果查看的是已读的消息,则去除掉未读的消息
                {
                    messages = messages.Except(noReadMessages).ToList();
                    messages.ForEach(t =>ChangeMessage(t));
                    GridMessage.DataSource = messages;
                }
                else
                {
                    noReadMessages.ForEach(t => ChangeMessage(t));
                    GridMessage.DataSource = messages;
                }
            }
        }
        private void ChangeMessage(Message message)
        {
            string from;
            allUsers.TryGetValue(Guid.Parse(message.From), out from);
            message.From = from;//转换消息来源

            string to;
            List<string> toids = message.To.Split(',').ToList();
            List<string> tonames = new List<string>();
            toids.ForEach(t => { allUsers.TryGetValue(Guid.Parse(t), out to); tonames.Add(to); });
            message.To = string.Join(",", tonames);//转换消息接受者

            string readUser;
            List<string> readids = message.ReadUser.Split(',').ToList();
            List<string> readnames = new List<string>();
            readids.ForEach(t => { allUsers.TryGetValue(Guid.Parse(t), out readUser); readnames.Add(readUser); });
            message.ReadUser = string.Join(",", readnames);//转换消息阅读者

            message.IsSendEmail = message.IsSendEmail == "1" ? "已读" : "未读";//转换是否发送邮件
        }

        private void menuShowClient_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
        }

        private void notifyMessage_DoubleClick(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
        }

        private void frmMessageMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!GlobalInfo.IsClosed)
            {
                this.WindowState = FormWindowState.Minimized;//关闭时窗体设置为最小化
                this.ShowInTaskbar = false;//不在任务栏显示图标
                notifyMessage.Visible = true;
                e.Cancel = true;//取消关闭窗体的操作
            }
        }

        private void btnNoRead_CheckedChanged(object sender, EventArgs e)
        {
            BindMessage();//重新绑定消息窗体
        }

        private void btnModelEdit_Click(object sender, EventArgs e)
        {
            frm_EditMessageModel frm_EditMessageModel = NinjectProvider.NinjectCore.GetService<frm_EditMessageModel>();
            frm_EditMessageModel.ShowDialog();

        }

        private void btnLinkUsers_Click(object sender, EventArgs e)
        {
            frm_EditLinkUser frm_EditLinkUser = NinjectProvider.NinjectCore.GetService<frm_EditLinkUser>();
            frm_EditLinkUser.ShowDialog();
        }

        private void tv_List_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (e.Action != TreeViewAction.ByMouse) return;//设置只有鼠标点击才有效,避免进入死循环
            foreach (TreeNode item in e.Node.Nodes)
            {
                item.Checked = e.Node.Checked;
            }
            if (e.Node.Parent == null)
            {
                return;
            }
            e.Node.Parent.Checked = false;
            foreach (TreeNode item in e.Node.Parent.Nodes)
            {
                if (item.Checked)
                {
                    e.Node.Parent.Checked = true;
                }
            }
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            if (GridMessage.SelectedRows.Count <= 0)
            {
                MessageBox.Show("请选择需要记录为已阅的消息!", "提示!");
                return;
            }
            bool isSuccess = false;
            using (IBLLMessageMain bLLMessageMain = NinjectProvider.NinjectCore.GetService<IBLLMessageMain>())
            {
                Guid id = Guid.Parse(GridMessage.SelectedRows[0].Cells["ID"].Value.ToString());
                isSuccess = bLLMessageMain.ReadMessage(id);
            }
            if (isSuccess)
            {
                BindMessage();
            }
        }

        private void btnReadAll_Click(object sender, EventArgs e)
        {

        }

        private void btnReturn_Click(object sender, EventArgs e)
        {
            if (GridMessage.SelectedRows.Count <= 0)
            {
                MessageBox.Show("请选择需要回复的消息!", "提示!");
                return;
            }
            frm_DealMessage frm_DealMessage = NinjectProvider.NinjectCore.GetService<frm_DealMessage>();
            frm_DealMessage.ID = Guid.Parse(GridMessage.SelectedRows[0].Cells[0].Value.ToString());
            frm_DealMessage.ShowDialog();
        }

        private void btnSendMessage_Click(object sender, EventArgs e)
        {
            frm_SendMessage frm_SendMessage = NinjectProvider.NinjectCore.GetService<frm_SendMessage>();
            frm_SendMessage.ShowDialog();
        }
        private List<string> GetSelectdUsers(TreeNode treeNode)
        {
            List<string> selectedUser =new List<string>();
            if (treeNode.Checked && treeNode.Tag != null)
            {
                selectedUser.Add(treeNode.Text);
            }
            if (treeNode.Nodes.Count > 0)
            {
                foreach (TreeNode item in treeNode.Nodes)
                    selectedUser.AddRange(GetSelectdUsers(item));
            }
            return selectedUser;
        }

        private void menuSendMessage_Click(object sender, EventArgs e)
        {
            List<string> selectedUsers = GetSelectdUsers(tv_List.Nodes[0]);
            if (selectedUsers.Count <= 0)
            {
                MessageBox.Show("请选择需要发送消息的用户!", "提示!");
                return;
            }
            frm_DealMessage frm_DealMessage = NinjectProvider.NinjectCore.GetService<frm_DealMessage>();
            frm_DealMessage.users = selectedUsers.ToArray();
            frm_DealMessage.ShowDialog();
        }
    }
}
